package com.cy.event;

import com.alibaba.fastjson.JSONObject;
import com.cy.common.Constant;
import com.cy.controller.LoginController;
import com.cy.entity.DiscussPost;
import com.cy.entity.Event;
import com.cy.entity.Message;
import com.cy.service.DiscussPostService;
import com.cy.service.ELService;
import com.cy.service.MessageService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: cy
 * @Date: 2022/02/05/21:21
 * @Description:   kafka消息消费者
 */
@Component
public class EventConsumer {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ELService elService;

    @KafkaListener(topics = {Constant.TOPIC_COMMENT, Constant.TOPIC_LIKE, Constant.TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record){
        if(record == null || record.value() == null){
            logger.error("消息内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null ){
            logger.error("消息格式错误！");
            return;
        }

        Message message = new Message();
        message.setFromId(Constant.SYSTEM_USER_ID);
        message.setToId(event.getEntityId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());


        //将event中数据拼接起来，存入content字段
        Map<String, Object> map = new HashMap<>();
        map.put("userId", event.getUserId());
        map.put("entityType", event.getEntityType());
        map.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            event.getData().forEach((k, v) -> {
                map.put(k, v);
            });
        }

        message.setContent(JSONObject.toJSONString(map));
        messageService.addMessage(message);
    }


    // 帖子添加到ElasticSearch
    @KafkaListener(topics = {Constant.TOPIC_PUBLIC})
    public void handlePublicMessage(ConsumerRecord record) {
        if(record == null || record.value() == null){
            logger.error("消息内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null ){
            logger.error("消息格式错误！");
            return;
        }

        DiscussPost discussPost = discussPostService.getById(event.getEntityId());
        elService.saveDiscussPost(discussPost);
    }


    // 消费删帖子事件
    @KafkaListener(topics = {Constant.TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        if(record == null || record.value() == null){
            logger.error("消息内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null ){
            logger.error("消息格式错误！");
            return;
        }

        elService.deleteDiscussPost(event.getEntityId());
    }

}
